package com.zlkj.pro.modular.business.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.auth.api.password.PasswordStoredEncryptApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.system.api.expander.SystemConfigExpander;
import cn.stylefeng.roses.kernel.system.api.pojo.user.SysUserDTO;
import cn.stylefeng.roses.kernel.system.api.pojo.user.request.SysUserRequest;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserRoleService;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlkj.pro.core.consts.ProjectConstants;
import com.zlkj.pro.core.exception.BusinessException;
import com.zlkj.pro.core.util.ConvertUtil;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.mapper.UserMapper;
import com.zlkj.pro.modular.admin.model.dto.DashboardDTO;
import com.zlkj.pro.modular.admin.model.dto.UserDTO;
import com.zlkj.pro.modular.admin.model.vo.UserVO;
import com.zlkj.pro.modular.admin.service.UsersService;
import com.zlkj.pro.modular.admin.service.impl.UsersServiceImpl;
import com.zlkj.pro.modular.business.mapper.AgentAccountMapper;
import com.zlkj.pro.modular.business.service.AgentAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.zlkj.pro.core.consts.ProjectConstants.ROLE_ID_YG;
import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.BUSINESS_EXCEPTION;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class AgentAccountServiceImpl extends ServiceImpl<UserMapper, User> implements AgentAccountService {

    @Autowired
    private AgentAccountMapper agentAccountMapper;

    @Autowired
    private Environment env;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private UsersService usersService;

    @Override
    public PageResult<UserVO> findPage(UserDTO dto) {
        Integer pageNo = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        dto.setUserId(LoginContext.me().getLoginUser().getUserId());
        // 角色赋值
        extracted(dto);

        List<UserVO> list = agentAccountMapper.findPage(dto);
        /*if(CollectionUtils.isNotEmpty(list)){
            list.forEach(vo -> {
                vo.setLogoUrl(env.getProperty("file-path") + vo.getLogoFileId());
            });
        }*/
        Long total = agentAccountMapper.findPageCount(dto);
        return PageResultFactory.createPageResult(list, total, pageSize, pageNo);
    }

    private void extracted(UserDTO dto) {
        SysUserRequest sysUserRequest = new SysUserRequest();
        sysUserRequest.setUserId(dto.getUserId());
        SysUserDTO currentUser = sysUserService.detail(sysUserRequest);
        Long roleId = currentUser.getGrantRoleIdList().get(0);
        if (ProjectConstants.ROLE_ID_BMSH_MANAGER.equals(roleId)) {
            dto.setRoleId(1L);
        } else if (ProjectConstants.ROLE_ID_BMSH_YG.equals(roleId)) {
            dto.setRoleId(2L);
        } else if (ProjectConstants.ROLE_ID_AGENT_MANAGER.equals(roleId)) {
            dto.setRoleId(3L);
        } else if (ProjectConstants.ROLE_ID_JL.equals(roleId)) {
            dto.setRoleId(4L);
        } else if (ROLE_ID_YG.equals(roleId)) {
            dto.setRoleId(5L);
        }
    }

    @Override
    public boolean edit(UserDTO dto) {

        // 根据手机号查询用户账号
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhone, dto.getPhone());
        queryWrapper.eq(User::getDelFlag, "N");
        queryWrapper.ne(User::getUserId, dto.getUserId());
        List<User> userList = super.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "手机号已经注册！");
        }

        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(User::getAccount, dto.getAccount());
        queryWrapper2.eq(User::getDelFlag, "N");
        queryWrapper2.ne(User::getUserId, dto.getUserId());
        List<User> userList2 = super.list(queryWrapper2);
        if (CollectionUtils.isNotEmpty(userList2)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "账号已经注册！");
        }

        // 修改为员工的时候不能选自己为上级经理
        if (dto.getRoleId() != null && dto.getRoleId().equals(ROLE_ID_YG)
                && dto.getLeaderId() != null
                && dto.getUserId().equals(dto.getLeaderId())) {
            throw new BusinessException(BUSINESS_EXCEPTION, "经理降级员工不可设置自己为上级经理！");
        }

        User entity = ConvertUtil.turn(dto, User.class);
        SysUserRequest request = new SysUserRequest();
        request.setUserId(dto.getUserId());
        request.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserService.grantRole(request);
        return super.updateById(entity);
    }

    @Override
    public boolean editPassWord(UserDTO dto) {
        User entity = new User();
        entity.setUserId(dto.getUserId());
        // 将密码加密存储到库中
        PasswordStoredEncryptApi passwordStoredEncryptApi = SpringUtil.getBean(PasswordStoredEncryptApi.class);
        entity.setPassword(passwordStoredEncryptApi.encrypt(dto.getPassword()));
        return super.updateById(entity);
    }

    @Override
    public boolean add(UserDTO dto) {
        // 查询当前用户角色信息
        LoginUser currentUser = LoginContext.me().getLoginUser();
        List<Long> userRole = sysUserRoleService.findRoleIdsByUserId(currentUser.getUserId());
        if (!userRole.contains(ProjectConstants.ROLE_ID_AGENT_MANAGER)
                && !userRole.contains(ProjectConstants.ROLE_ID_JL)) {
            // 非代理商管理员 即BMSH 角色只能添加代理商管理员账号
            dto.setRoleId(ProjectConstants.ROLE_ID_AGENT_MANAGER);
            // 一个代理商只能有一个管理员
            UserDTO checkParam = new UserDTO();
            checkParam.setAgentId(dto.getAgentId());
            checkParam.setRoleId(ProjectConstants.ROLE_ID_AGENT_MANAGER);
            List<UserVO> managers = agentAccountMapper.findManager(checkParam);
            if (CollectionUtils.isNotEmpty(managers)) {
                throw new BusinessException(BUSINESS_EXCEPTION, "该代理商已经有管理员了！");
            }
        }

        //User entity = ConvertUtil.turn(dto, User.class);
        // 校验逻辑
        /*if (dto.getPassword() == null || dto.getPassword().length() < 6) {
            throw new BusinessException(BUSINESS_EXCEPTION, "密码最少六位");
        }*/

        // 根据手机号查询用户账号
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhone, dto.getPhone());
        queryWrapper.eq(User::getDelFlag, "N");
        List<User> userList = super.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "手机号已经注册！");
        }
        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(User::getAccount, dto.getAccount());
        queryWrapper2.eq(User::getDelFlag, "N");
        List<User> userList2 = super.list(queryWrapper2);
        if (CollectionUtils.isNotEmpty(userList2)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "账号已经注册！");
        }

        // 创建账号
        SysUserRequest sysUserRequest = ConvertUtil.turn(dto, SysUserRequest.class);
        sysUserRequest.setUserId(IdUtil.getSnowflake().nextId());
        sysUserRequest.setNickName(sysUserRequest.getRealName());
        sysUserRequest.setBirthday("2020-01-01");
        sysUserRequest.setSex("M");
        sysUserRequest.setEmail(" ");
        sysUserRequest.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserRequest.setPositionId(ProjectConstants.DEFAULT_POSITION_ID);//默认职位
        sysUserRequest.setStatusFlag(1);
        sysUserRequest.setOrgId(ProjectConstants.DEFAULT_ORG_ID);//默认添加到总公司下面
        sysUserRequest.setGrantOrgIdList(Collections.singletonList(ProjectConstants.DEFAULT_ORG_ID));
        sysUserService.add(sysUserRequest);

        // 补充代理商信息
        User user = new User();
        user.setUserId(sysUserRequest.getUserId());
        user.setStatusFlag(1);//启用
        user.setAgentId(dto.getAgentId());//设置用户代理商信息
        if (dto.getLeaderId() != null) {
            user.setLeaderId(dto.getLeaderId());
        }
        super.updateById(user);

        // 授权角色
        SysUserRequest request = new SysUserRequest();
        request.setUserId(sysUserRequest.getUserId());
        request.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserService.grantRole(request);

        return true;
    }

    @Override
    public List<UserVO> findManagers(UserDTO dto) {
        // 获取用户代理商 ID
        //UserDTO userDto = new UserDTO();
        //userDto.setUserId(LoginContext.me().getLoginUser().getUserId());
        //UserVO userVo = usersService.detail(userDto);
        // 前端选择了代理商使用前端的代理商条件筛选经理人
        // 前端未选择代理商查询全部什么都不返回
        if (dto.getAgentId() == null) {
            return new ArrayList<UserVO>();
        }
        //dto.setAgentId(userVo.getAgentId());
        return agentAccountMapper.findManagers(dto);
    }

    /*@Override
    public List<AgentVO> findList(AgentDTO dto) {
        LambdaQueryWrapper<AgentEntity> productInfoEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
        productInfoEntityLambdaQueryWrapper.orderByDesc(AgentEntity::getCreateTime);
        List<AgentEntity> productInfoEntityList = super.list(productInfoEntityLambdaQueryWrapper);
        return ConvertUtil.turn(productInfoEntityList, AgentVO.class);
    }

    @Override
    public AgentVO findDetail(AgentDTO dto) {
        Long id = dto.getId();
        LambdaQueryWrapper<AgentEntity> productInfoEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
        productInfoEntityLambdaQueryWrapper.eq(AgentEntity::getId, id);
        AgentEntity productInfoEntity = super.getOne(productInfoEntityLambdaQueryWrapper, Boolean.FALSE);
        return ConvertUtil.turn(productInfoEntity, AgentVO.class);
    }

    @Override
    public boolean delete(AgentDTO dto) {
        return super.removeById(dto);
    }

    @Override
    public boolean batchDelete(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            return super.removeByIds(ids);
        }
        return true;
    }*/

}
